package startup

import (
	"context"
	"encoding/json"
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/http_server/middleware"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/http_server/router"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common/utils"
	"git.mycaigou.com/ycg/go2sky-plugins/gin/v3"
	"git.mycaigou.com/ycg/stark-extend/go2skyplugins"
	"git.myscrm.cn/golang/common/ykenv"
	"git.myscrm.cn/golang/common/ykerrcode"
	"github.com/gin-gonic/gin"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
	grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"
	"strings"
)

// RegisterGRPCServer 此处注册pb的Server
func RegisterGRPCServer(grpcServer *grpc.Server) error {
	//s := grpcServer
	//
	//inject := di.NewInject()
	//err := inject.Invoke(func(userInfoServer pb.UserInfoServiceServer) {
	//	pb.RegisterUserInfoServiceServer(s, userInfoServer)
	//})
	//
	//if err != nil {
	//	fmt.Printf("RegisterGRPCServer err: %+v\n", err)
	//	return err
	//}

	fmt.Printf("RegisterGRPCServer successful\n")
	return nil
}

// RegisterGateway 此处注册pb的Gateway
func RegisterGateway(ctx context.Context, gateway *runtime.ServeMux, endPoint string, dopts []grpc.DialOption) error {
	//var err error
	//if err = pb.RegisterUserInfoServiceHandlerFromEndpoint(ctx, gateway, endPoint, dopts); err != nil {
	//	return err
	//}
	//if err = pb.RegisterUserLoginServiceHandlerFromEndpoint(ctx, gateway, endPoint, dopts); err != nil {
	//	return err
	//}
	return nil
}

func RegisterMiddleware() []grpc.UnaryServerInterceptor {
	myAuthFunction := func(ctx context.Context) (context.Context, error) {
		bearer, err := grpc_auth.AuthFromMD(ctx, "bearer")
		splits := strings.SplitN(bearer, ".", 2)
		if len(splits) < 2 {
			return nil, ykerrcode.TogRPCError(
				errcode.COMMON_TOKEN_ERROR, fmt.Sprintf("bearer is null, bearer: %s, err: %+v", bearer, err))
		}

		//token := splits[0]
		data := splits[1]

		authInfo := utils.AuthInfo{}
		err = json.Unmarshal([]byte(data), &authInfo)
		if err != nil {
			return nil, ykerrcode.TogRPCError(errcode.COMMON_TOKEN_ERROR, err.Error())
		}
		//
		//acUsercase := di.NewAccessTokenDi()

		// WARNING: in production define your own type to avoid context collisions
		newCtx := context.WithValue(ctx, "app_id", authInfo)
		return newCtx, nil
	}

	unaryInterceptor := grpc_middleware.ChainUnaryServer(
		grpc_ctxtags.UnaryServerInterceptor(),
		grpc_auth.UnaryServerInterceptor(myAuthFunction),
	)

	return []grpc.UnaryServerInterceptor{unaryInterceptor}
}

// RegisterHttpRoute 此处注册 gin 接口
func RegisterHttpRoute(r *gin.Engine) error {
	r.Use(gin.Recovery())
	//跨域请求
	r.Use(middleware.Cors())
	//访问日志
	r.Use(middleware.AccessLogs())

	// 链路接入
	tracer, err := go2skyplugins.GetTracer()
	if err != nil {
		fmt.Println("go2skyplugins.GetTracer err:", err.Error())
	} else {
		r.Use(v3.Middleware(r, tracer)) // r是*gin.Engine
	}
	//健康检测接口
	healthGroup := r.Group("/")
	router.RegisterHealthRouters(healthGroup)
	r.Any("/", func(c *gin.Context) {
		c.JSON(0, map[string]interface{}{
			"message": "ok",
		})
	})

	authGroup := r.Group("/auth")
	router.RegisterAuthRouters(authGroup)

	//服务访问认证拦截器
	if !ykenv.IsDevMode() {
		r.Use(middleware.ServiceAuthorize())
	}

	bigdataGroup := r.Group("/big-data")
	router.RegisterBigdataRouters(bigdataGroup)

	writeGroup := r.Group("/write")
	router.RegisterWriteRouters(writeGroup)

	opptyGroup := r.Group("/oppty")
	router.RegisterOpptyRouters(opptyGroup)

	//用户信息连接器
	//r.Use(middleware.HeaderUserInfoToMetadata())
	//租户服务拦截器
	//r.Use(middleware.TenantDb())

	return nil
}
